<template>
  <div class="join-addEdit">
    <el-dialog :append-to-body="true" title="审核书籍" v-model="show" @close="cancelFun" :close-on-click-modal="false"
      destroy-on-close>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="130px" class="demo-ruleForm">
        <el-form-item label="图片:" prop="images" style="height: auto">
          <el-upload :http-request="upload" action="" list-type="picture-card" :on-preview="imgPreview"
            :on-remove="imgRemove" :file-list="form.images" accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF" :limit="1"
            :on-exceed="limitFun">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="书籍成功数量:" prop="count">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.count" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="书籍不符合原因:" prop="context">
          <el-select v-model="form.context" class="m-2" placeholder="状态" size="large" style="width: 100%;">
            <el-option v-for="item in lists" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFun" size="large">取消</el-button>
          <el-button type="primary" @click="confirmFun" size="large">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog :append-to-body="true" v-model="showImages">
      <img style="width: 100%" :src="imageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, onMounted, onUnmounted, ref, watch, defineEmits, reactive } from 'vue'
import { addServerUser, editServerUser } from '@api/person'
import { addShangpin, editShangpin } from '@api/book'
import { encode } from 'js-base64'
import md5 from 'js-md5'
import { ElMessage } from 'element-plus'
import * as qiniu from 'qiniu-js'
import { useQiniuStore } from '@/pinia/qiniu'
import { getShujiType } from '@api/bookType'
import { getServerUserList } from '@api/person'
import { getToken, getIsbn } from '@api/common'
import { updateOrderItemShenghe } from '@api/order'
import { getOrderJuqianList } from '@api/reason'

const qiniuStore = useQiniuStore()

const props = defineProps({
  id: {
    type: String,
    default: null
  },
  show: {
    type: Boolean,
    default: null
  },
  count: {
    type: Number,
    default: null
  }
})

const formRef = ref()

const form = ref({
  images: [],
  count: 0,
  context: ''
})

const rules = reactive({
  context: [{ required: true, message: '备注不能为空!', trigger: 'blur' }],
  count: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.value.count
        if (!value) {
          callback(new Error('数量不能为空!'))
        } else if (!/^[+]?(0|([1-9]\d*))(\.\d+)?$/g.test(value)) {
          callback(new Error('请输入数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['hide-addEdit'])

const title = computed(() => {
  return props.status == 'add' ? '添加书籍' : '编辑书籍'
})

// 添加或编辑
function confirmFun() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = ''
      let { images, count, context } = form.value
      images = images.map((v) => v.url).join(',')

      let data = {
        id: props.id,
        count,
        context,
        images
      }

      res = await updateOrderItemShenghe(data)

      if (res.code == 200) {
        ElMessage({
          message: '操作成功!',
          type: 'success'
        })
        emit('hide-addEdit', props.status)
      }
    }
  })
}

function cancelFun() {
  emit('hide-addEdit', 'cancel')
}

//获取列表
let token = ''
async function getQiNiuToken() {
  let res = await getToken()
  token = res.data.token
}

//上传多个
const uploadMultiple = async (file, name) => {
  /*
  bucket: 上传的目标空间

  file: File 对象，上传的文件

  key: 文件资源名

  token: 上传验证信息，前端通过接口请求后端获得

  config: object，其中的每一项都为可选
*/

  // qiniu.upload(file: File, key: string, token: string, putExtra?: object, config?: object): observable
  const key = new Date().getTime()
  const observable = qiniu.upload(file, key, token)
  const subscription = observable.subscribe({
    next: (result) => {
      // 接收上传进度信息，result是带有total字段的 Object
      // loaded: 已上传大小; size: 上传总信息; percent: 当前上传进度
      console.log(result) // 形如：{total: {loaded: 1671168, size: 2249260, percent: 74.29856930723882}}
      // this.percent = result.total.percent.toFixed(0);
    },
    error: (errResult) => {
      // 上传错误后失败报错
      console.log(errResult)
      // this.message.error('上传失败');
    },
    complete: (result) => {
      // 接收成功后返回的信息

      if (result.key) {
        form.value.images = [
          {
            name: qiniuStore.qiniu + result.key,
            url: qiniuStore.qiniu + result.key
          }
        ]

        ElMessage({
          message: '上传成功!',
          type: 'success'
        })
      }
    }
  })
}

//上传
const loading = ref()
const upload = async (params) => {
  let that = this
  //限制图片大小
  let size = params.file.size / 1024 / 1024 < 4

  if (!size) {
    this.$message.error('上传图片的大小不能超过 4M!')
    return false
  }

  // loading.value = ElLoading.service({
  //   lock: true,
  //   text: '加载中'
  // })

  // let thisRef = 'imgComRef';
  // let uploadFile = "";
  // uploadFile = this.$refs[thisRef].uploadFiles;

  // this.$refs[thisRef].clearFiles();

  //上传控件的最后一个文件信息
  // let len = uploadFile.length;
  // let file = uploadFile[len - 1].raw;
  // let uid = uploadFile[len - 1].uid;
  // let name = uploadFile[len - 1].name;
  await uploadMultiple(params.file)
}

//超出限制
function limitFun() {
  ElMessage.error('最多上传1张!')
}
//图片删除
function imgRemove(file, filelist) {
  form.value.image = []
}
//图片预览
const imageUrl = ref('')
const showImages = ref(false)
function imgPreview(file) {
  imageUrl.value = file.url
  showImages.value = true
}

//获取列表
const lists = ref([])
const getLists = async () => {
  let res = await getOrderJuqianList()

  if (res.code == 200) {
    lists.value = res.data.map((v) => {
      return {
        label: v.name,
        value: v.id
      }
    })
    form.value.context = lists.value.length ? lists.value[0].label : ''
  }
}

onMounted(() => { })

watch(
  () => props.show,
  (newValue, oldValue) => {
    form.value.count = props.count
    getQiNiuToken()
    getLists()
  },
  { deep: true }
)
</script>
<style lang="scss" scoped>
.news-addEdit {}
</style>
